package com.yndsoft.jc.supplier.info;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.annotation.DrawableRes;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.yndsoft.jc.R;
import com.yndsoft.jc.model.ReturnMsg;
import com.yndsoft.jc.supplier.base.SupplierBaseActivity;
import com.yndsoft.jc.supplier.join.PopupWindowAddress;
import com.yndsoft.jc.supplier.model.AccountModel;
import com.yndsoft.jc.supplier.model.HeadModel;
import com.yndsoft.jc.supplier.model.SupplierInfoModel;
import com.yndsoft.jc.supplier.modelput.Supplier;
import com.yndsoft.jc.supplier.modelput.SupplierUpdate;
import com.yndsoft.jc.supplier.net.ApiService;
import com.yndsoft.jc.supplier.net.util.ProgressSubscriber;
import com.yndsoft.jc.supplier.utils.Base64UploadImg;
import com.yndsoft.jc.supplier.utils.Constants;
import com.yndsoft.jc.supplier.utils.GlideCircleTransform;
import com.yndsoft.jc.supplier.utils.MaxLengthWatcher;
import com.yndsoft.jc.supplier.utils.RegexUtil;
import com.yndsoft.jc.supplier.utils.ToastUtil;
import com.yndsoft.jc.supplier.widget.imageselector.ImageLoader;
import com.yndsoft.jc.supplier.widget.imageselector.ImgSelActivity;
import com.yndsoft.jc.supplier.widget.imageselector.ImgSelConfig;
import com.yndsoft.jc.supplier.widget.popupwindow.OnChooseDataListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

public class SupplierInfoActivity extends SupplierBaseActivity implements View.OnClickListener, View.OnTouchListener {

    private ImageView supplierInfoHead;
    private TextView supplierInfoNick;
    private EditText supplierInfoContact;
    private EditText supplierInfoMail;
    private ImageView supplierInfoCard;
    private TextView supplierInfoAccount;
    private TextView supplierInfoWay;
    private EditText supplierInfoName;
    private TextView supplierInfoAddress;
    private EditText supplierInfoDetailAddress;
    private ImageView supplierInfoLicence;
    private EditText supplierInfoIntro;
    private LinearLayout supplierInfoRoot;
    private ImageLoader loader = new ImageLoader() {
        @Override
        public void displayImage(Context context, String path, ImageView imageView) {
            Glide.with(context)
                    .load(path)
                    .placeholder(R.drawable.ic_default_image)
                    .centerCrop()
                    .into(imageView);
        }
    };

    private String headImgPath = null;
    private String cardImgPath = null;
    private String licenceImgPath = null;
    private String name;
    private String user;
    private String account;
    private int provinceKey = 0;
    private String provinceValue = "";
    private int cityKey = 0;
    private String cityValue = "";
    private int districtKey = 0;
    private String districtValue = "";
    private SupplierInfoModel model;
    private int collectStatus;
    private String nameValue;

    @Override
    public int getContentResId() {
        return R.layout.activity_supplier_info;
    }

    public static void start(Context context) {
        context.startActivity(new Intent(context, SupplierInfoActivity.class));
    }

    @Override
    public void initView() {
        ImageButton barBack = findViewById(R.id.bar_back);
        TextView barTitle = findViewById(R.id.bar_title);
        supplierInfoHead = findViewById(R.id.supplier_info_head);
        supplierInfoNick = findViewById(R.id.supplier_info_nick);
        RelativeLayout supplierInfo = findViewById(R.id.supplier_info);
        supplierInfoContact = findViewById(R.id.supplier_info_contact);
        supplierInfoMail = findViewById(R.id.supplier_info_mail);
        supplierInfoCard = findViewById(R.id.supplier_info_card);
        RelativeLayout supplierCard = findViewById(R.id.supplier_card);
        supplierInfoAccount = findViewById(R.id.supplier_info_account);
        LinearLayout supplierAccount = findViewById(R.id.supplier_account);
        supplierInfoWay = findViewById(R.id.supplier_info_way);
        LinearLayout supplierWay = findViewById(R.id.supplier_way);
        supplierInfoName = findViewById(R.id.supplier_info_name);
        supplierInfoAddress = findViewById(R.id.supplier_info_address);
        LinearLayout supplierAddress = findViewById(R.id.supplier_address);
        supplierInfoDetailAddress = findViewById(R.id.supplier_info_detail_address);
        supplierInfoLicence = findViewById(R.id.supplier_info_licence);
        RelativeLayout supplierLicence = findViewById(R.id.supplier_licence);
        supplierInfoIntro = findViewById(R.id.supplier_info_intro);
        Button supplierInfoSave = findViewById(R.id.supplier_info_save);
        supplierInfoRoot = findViewById(R.id.supplier_info_root);

        barTitle.setText("我的资料");
        barBack.setOnClickListener(this);
        supplierInfo.setOnClickListener(this);
        supplierCard.setOnClickListener(this);
        supplierAccount.setOnClickListener(this);
        supplierWay.setOnClickListener(this);
        supplierAddress.setOnClickListener(this);
        supplierLicence.setOnClickListener(this);
        supplierInfoSave.setOnClickListener(this);
        supplierInfoIntro.setOnTouchListener(this);
        supplierInfoIntro.addTextChangedListener(new MaxLengthWatcher(100, supplierInfoIntro));

    }

    @Override
    public void initData() {
        EventBus.getDefault().register(this);
        mHttpUtil.supplierInfo(new ProgressSubscriber(mContext) {
            @Override
            public void next(ReturnMsg returnMsg) {
                String info = returnMsg.getInfo();
                if (info != null) {
                    SupplierInfoModel model = new Gson().fromJson(info, SupplierInfoModel.class);
                    if (model != null) {
                        loadData(model);
                    }
                }
            }
        }, "supplier", mSession.getSid());
    }

    private void loadData(SupplierInfoModel model) {
        this.model = model;
        supplierInfoNick.setText(model.getName() != null ? model.getName() : "");
        Glide.with(mContext).load(ApiService.BASE_URL + model.getImg()).transform(new GlideCircleTransform(mContext)).placeholder(R.mipmap.product_img).into(supplierInfoHead);
        supplierInfoContact.setText(model.getContactname() != null ? model.getContactname() : "");
        supplierInfoMail.setText(model.getEmail() != null ? model.getEmail() : "");
        Glide.with(mContext).load(ApiService.BASE_URL + model.getFrimg()).into(supplierInfoCard);

        int accounttype = model.getAccounttype();
        if (accounttype == 3) {
            setIcon(R.mipmap.unionpay_small);
            String zh = model.getYhkhm() != null ? model.getYhkhm() + " " : "";
            zh = zh + (model.getKhyhzh() != null ? model.getKhyhzh() : "");
            supplierInfoAccount.setText(zh);
        } else if (accounttype == 1) {
            setIcon(R.mipmap.alipay_small);
            supplierInfoAccount.setText(model.getAlipay() != null ? model.getAlipay() : "");
        } else if (accounttype == 2) {
            setIcon(R.mipmap.wechat_small);
            supplierInfoAccount.setText(model.getWeixinpay() != null ? model.getWeixinpay() : "");
        }
        supplierInfoWay.setText(model.getPaytype() == 2 ? "人工申请" : "自动收款");
        supplierInfoName.setText(model.getName() != null ? model.getName() : "");
        String mergeCity = model.getProvince() != null ? model.getProvince() + " " : "";
        mergeCity = mergeCity + (model.getCity() != null ? model.getCity() + " " : "");
        mergeCity = mergeCity + (model.getDistrict() != null ? model.getDistrict() : "");
        supplierInfoAddress.setText(mergeCity);
        supplierInfoDetailAddress.setText(model.getAddress() != null ? model.getAddress() : "");
        Glide.with(mContext).load(ApiService.BASE_URL + model.getYyzzimg()).into(supplierInfoLicence);
        supplierInfoIntro.setText(model.getBusiness() != null ? model.getBusiness() : "");
    }

    private void setIcon(@DrawableRes int resId) {
        Drawable drawable = getResources().getDrawable(resId);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        supplierInfoAccount.setCompoundDrawables(drawable, null, null, null);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bar_back:
                finish();
                break;
            case R.id.supplier_info:
                chooseHead(Constants.REQUEST_HEAD_CODE);
                break;
            case R.id.supplier_card:
                chooseAlbum(Constants.REQUEST_CARD_CODE);
                break;
            case R.id.supplier_account:
                SupplierAccount.start(mContext);
                break;
            case R.id.supplier_way:
                int status = 1;
                if ("人工申请".equals(supplierInfoWay.getText().toString())) {
                    status = 2;
                }
                PayWay.start(mContext, status);
                break;
            case R.id.supplier_address:
                PopupWindowAddress address = new PopupWindowAddress(mContext, supplierInfoAddress.getText().toString());
                address.showAtLocation(supplierInfoRoot, Gravity.BOTTOM, 0, 0);
                address.setOnChooseDataListener(new OnChooseDataListener() {
                    @Override
                    public void onChooseData(int key1, String value1, int key2, String value2, int key3, String value3) {
                        supplierInfoAddress.setText(value1 + " " + value2 + " " + value3);
                        provinceKey = key1;
                        provinceValue = value1;
                        cityKey = key2;
                        cityValue = value2;
                        districtKey = key3;
                        districtValue = value3;
                    }
                });
                break;
            case R.id.supplier_licence:
                chooseAlbum(Constants.REQUEST_LICENCE_CODE);
                break;
            case R.id.supplier_info_save:
                String contactValue = supplierInfoContact.getText().toString().trim();
                String mailValue = supplierInfoMail.getText().toString().trim();
                nameValue = supplierInfoName.getText().toString().trim();
                String detailAddressValue = supplierInfoDetailAddress.getText().toString().trim();
                String introValue = supplierInfoIntro.getText().toString().trim();
                if (TextUtils.isEmpty(contactValue)) {
                    showHint("请输入联系人姓名！");
                } else {
                    if (TextUtils.isEmpty(mailValue)) {
                        showHint("请输入联系人邮箱！");
                    } else {
                        if (!RegexUtil.isEmail(mailValue)) {
                            showHint("邮箱格式错误！");
                        } else {
                            if (TextUtils.isEmpty(nameValue)) {
                                showHint("请输入机构名称！");
                            } else {
                                if (TextUtils.isEmpty(detailAddressValue)) {
                                    showHint("请输入详细地址！");
                                } else {
                                    if (TextUtils.isEmpty(introValue)) {
                                        showHint("请输入机构简介！");
                                    } else {
                                        SupplierUpdate supplier = new SupplierUpdate();
                                        supplier.setId(model.getId());
                                        supplier.setContactname(contactValue);
                                        supplier.setEmail(mailValue);
                                        headImgPath = headImgPath != null ? headImgPath : model.getImg();
                                        supplier.setImg(headImgPath);
                                        supplier.setFrimg(cardImgPath != null ? cardImgPath : model.getFrimg());
                                        if (0 != collectStatus) {
                                            supplier.setAccounttype(String.valueOf(collectStatus));
                                            switch (collectStatus) {
                                                case 3:
                                                    supplier.setKhyhzh(name);
                                                    supplier.setYhkhm(user);
                                                    supplier.setGsyhzh(account);
                                                    break;
                                                case 1:
                                                    supplier.setAlipay(name);
                                                    break;
                                                case 2:
                                                    supplier.setWeixinpay(name);
                                                    break;
                                            }
                                        } else {
                                            supplier.setAccounttype(model.getAccounttype() + "");
                                            switch (model.getAccounttype()) {
                                                case 3:
                                                    supplier.setKhyhzh(model.getKhyhzh());
                                                    supplier.setYhkhm(model.getYhkhm());
                                                    supplier.setGsyhzh(model.getGsyhzh());
                                                    break;
                                                case 1:
                                                    supplier.setAlipay(model.getAlipay());
                                                    break;
                                                case 2:
                                                    supplier.setWeixinpay(model.getWeixinpay());
                                                    break;
                                            }
                                        }
                                        supplier.setPaytype("自动收款".equals(supplierInfoWay.getText().toString()) ? "1" : "2");
                                        supplier.setName(nameValue);
                                        if ("".equals(provinceValue) || "".equals(cityValue) || "".equals(districtValue)) {
                                            supplier.setProvinceid(model.getProvinceid() + "");
                                            supplier.setProvince(model.getProvince());
                                            supplier.setCityid(model.getCityid() + "");
                                            supplier.setCity(model.getCity());
                                            supplier.setDistrictid(model.getDistrictid() + "");
                                            supplier.setDistrict(model.getDistrict());
                                        } else {
                                            supplier.setProvinceid(String.valueOf(provinceKey));
                                            supplier.setProvince(provinceValue);
                                            supplier.setCityid(String.valueOf(cityKey));
                                            supplier.setCity(cityValue);
                                            supplier.setDistrictid(String.valueOf(districtKey));
                                            supplier.setDistrict(districtValue);
                                        }
                                        supplier.setAddress(detailAddressValue);
                                        supplier.setYyzzimg(licenceImgPath != null ? licenceImgPath : model.getYyzzimg());
                                        supplier.setBusiness(introValue);
                                        String supplierJsonValue = new Gson().toJson(supplier);
                                        putSupplierInfo(supplierJsonValue);
                                    }
                                }
                            }
                        }
                    }
                }
                break;
        }
    }

    private void putSupplierInfo(String json) {
        mHttpUtil.put(new ProgressSubscriber(mContext) {
            @Override
            public void next(ReturnMsg returnMsg) {
                if (1 == returnMsg.getCode()) {
//                    HeadModel model = new HeadModel();
//                    model.setCode(1);
//                    model.setHead(headImgPath);
//                    model.setName(nameValue);
//                    EventBus.getDefault().post(model);
                    ToastUtil.show(mContext, "保存成功");
                    finish();
                } else {
                    ToastUtil.show(mContext, "保存失败");
                }
            }
        }, "edit", json);
    }

    private void chooseHead(int requestCode) {
        ImgSelConfig config = new ImgSelConfig.Builder(this, loader)
                .multiSelect(false)
                .rememberSelected(false)
                .cropSize(1, 1, 200, 200)
                .needCrop(true)
                .needCamera(true)
                .maxNum(1)
                .build();
        ImgSelActivity.startActivity(this, config, requestCode);
    }

    private void chooseAlbum(int requestCode) {
        ImgSelConfig config = new ImgSelConfig.Builder(this, loader)
                .multiSelect(false)
                .rememberSelected(false)
                .needCamera(true)
                .maxNum(1)
                .build();
        ImgSelActivity.startActivity(this, config, requestCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            switch (requestCode) {
                case Constants.REQUEST_HEAD_CODE:
                    List<String> headPathList = data.getStringArrayListExtra(ImgSelActivity.INTENT_RESULT);
                    if (headPathList != null && headPathList.size() > 0) {
                        String path = headPathList.get(0);
                        if (path != null) {
                            Glide.with(mContext).load("file://" + path).transform(new GlideCircleTransform(mContext)).into(supplierInfoHead);
                            Base64UploadImg base64UploadImg = new Base64UploadImg();
                            base64UploadImg.uploadImg(mContext, path);
                            base64UploadImg.setOnUpImgListener(new Base64UploadImg.OnUpImgListener() {
                                @Override
                                public void onUpImg(String imgBase64) {
                                    headImgPath = imgBase64;
                                }
                            });
                        }
                    }
                    break;
                case Constants.REQUEST_CARD_CODE:
                    List<String> cardPathList = data.getStringArrayListExtra(ImgSelActivity.INTENT_RESULT);
                    if (cardPathList != null && cardPathList.size() > 0) {
                        String path = cardPathList.get(0);
                        if (path != null) {
                            Glide.with(mContext).load("file://" + path).into(supplierInfoCard);
                            Base64UploadImg base64UploadImg = new Base64UploadImg();
                            base64UploadImg.uploadImg(mContext, path);
                            base64UploadImg.setOnUpImgListener(new Base64UploadImg.OnUpImgListener() {
                                @Override
                                public void onUpImg(String imgBase64) {
                                    cardImgPath = imgBase64;
                                }
                            });
                        }
                    }
                    break;
                case Constants.REQUEST_LICENCE_CODE:
                    List<String> licencePathList = data.getStringArrayListExtra(ImgSelActivity.INTENT_RESULT);
                    if (licencePathList != null && licencePathList.size() > 0) {
                        String path = licencePathList.get(0);
                        if (path != null) {
                            Glide.with(mContext).load("file://" + path).into(supplierInfoLicence);
                            Base64UploadImg base64UploadImg = new Base64UploadImg();
                            base64UploadImg.uploadImg(mContext, path);
                            base64UploadImg.setOnUpImgListener(new Base64UploadImg.OnUpImgListener() {
                                @Override
                                public void onUpImg(String imgBase64) {
                                    licenceImgPath = imgBase64;
                                }
                            });
                        }
                    }
                    break;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 100)
    public void onEvent(AccountModel model) {
        if (model != null) {
            switch (model.getFunction()) {
                case 1:
                    collectStatus = model.getStatus();
                    switch (collectStatus) {
                        case 3:
                            name = model.getName();
                            user = model.getUser();
                            account = model.getAccount();
                            setIcon(R.mipmap.unionpay_small);
                            supplierInfoAccount.setText(user + " " + name);
                            break;
                        case 1:
                            name = model.getName();
                            setIcon(R.mipmap.alipay_small);
                            supplierInfoAccount.setText(name);
                            break;
                        case 2:
                            name = model.getName();
                            setIcon(R.mipmap.wechat_small);
                            supplierInfoAccount.setText(name);
                            break;
                    }
                    break;
                case 2:
                    supplierInfoWay.setText(model.getStatus() == 1 ? "自动收款" : "人工申请");
                    break;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        onEvent(new AccountModel());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        switch (view.getId()) {
            case R.id.info_intro:
                view.getParent().requestDisallowInterceptTouchEvent(true);
                switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
                    case MotionEvent.ACTION_UP:
                        view.getParent().requestDisallowInterceptTouchEvent(false);
                        break;
                }
        }
        return false;
    }
}
